package com.crm.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.crm.entity.Director;
import com.crm.entity.CompanyEntity;
import com.crm.service.DirectorService;
import com.crm.service.EntityService;
import com.microsoft.playwright.*;
import com.microsoft.playwright.options.LoadState;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
public class RunnablePlaywright {


    @Autowired
    private DirectorService directorService;

    @Autowired
    private EntityService entityService;

    private static final Logger logger = LoggerFactory.getLogger(RunnablePlaywright.class);

    // 标记异步方法
    @Async
    public void startTask(int start, int end) {
        this.startTask("Thread" + start, start, end);

    }

    @Async
    public void startTask(String name, int start, int end) {
        logger.info("Creating " + name + ",start:" + start + ",end:" + end);

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true).setSlowMo(250).setTimeout(40000));
            Page page = browser.newPage();
            page.navigate("https://www.businessregistration.moc.gov.kh/");
            page.click("a[class=\"menu-toggle injected\"]");
            page.click("text=Search Entity");

            for (int j = start; j < end; j++) {
                System.out.println(j + "|" + "执行搜索字符串填入");
                String queryString = ("000000000" + j).substring(("000000000" + j).length() - 8);
//                queryString="00000002";
                System.out.println("按钮点击" + "|" + queryString);
                while (true) {
                    page.waitForTimeout(1000);
                    if (page.locator("input[name=\"QueryString\"]").isVisible()) {
                        page.fill("input[name=\"QueryString\"]", queryString);
                        break;
                    }
                }
//                page.fill("input[name=\"QueryString\"]", "00000178");
                try {

//                page.click("text=Search");
                    System.out.println("按钮执行完毕");

                    page.waitForResponse("**/cambodia-master/viewInstance/update.html*", () -> {
                        page.locator("//div[@class=\"appTabSelected\"]").locator("span:text-is(\"Search\")").click();
                    });
                    page.waitForTimeout(2000);
                    page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));

                    String first = "//body/div[1]/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[4]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/a[1]/span[2]";
                    Locator firstLocator = page.locator(first);

                    if (firstLocator.isVisible()) {
                        System.out.println("数据获取开始");
                        firstLocator.click();
                        page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                        CompanyEntity companyEntity = new CompanyEntity();
                        companyEntity.setBusinessId(queryString);
                        Thread.sleep(1000);
//                    hashMap.put()
                        // //li[@class="appTabPostSelected"]/a[1]/span[1]
//                    map.put("CompanyNameInKhmer",page.locator("//div[@class=\"appRepeaterRo
//                    wContent appRowOdd appRowFirst appRowLast\"]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                        // 获取紧邻的下一个同级div
                        //page.evaluate("div[css*=\"brViewOverseasCompany-tabsBox-detailsTab-details-historicalInformationBox\"]");
                        ElementHandle element = page.querySelector(".brViewOverseasCompany-tabsBox-detailsTab-details-historicalInformationBox");
                        if (element != null) {
                            element.evaluate("node => node.remove()");
                            element.dispose(); // 释放资源
                            System.out.println("删除历史记录");
                        }
                        Locator detailLocator;
                        if (page.locator("text=\"Show company name history\"").isVisible()) {
                            System.out.println("Show company name history");
                            detailLocator = page.locator("div[css*=\"brViewLocalCompany-tabsBox-detailsTabChangedPOC-details-localDetailsBox\"]");
                        } else {
                            detailLocator = page.locator("body");
                        }

//                        Locator detailLocator = page.locator("div[css*=\"brViewLocalCompany-tabsBox-detailsTabChangedPOC-details\"]");
                        if (detailLocator.locator("div[id*=\"Name_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setCompanyNameInEnglish(detailLocator.locator("div[id*=\"Name_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"NameInKhmer_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setProposedNameInKhmer(detailLocator.locator("div[id*=\"NameInKhmer_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"OriginalVersionIdentifier_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setOriginalEntityIdentifier(detailLocator.locator("div[id*=\"OriginalVersionIdentifier_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"Status_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setCompanyStatus(detailLocator.locator("div[id*=\"Status_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"-RegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                            companyEntity.setIncorporationDate(detailLocator.locator("div[id*=\"-RegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"TIN_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setTaxIdentificationNumber(detailLocator.locator("div[id*=\"TIN_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"TINRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                            companyEntity.setTaxRegistrationDate(detailLocator.locator("div[id*=\"TINRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"LatestAnnualFiling_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                            companyEntity.setAnnualReturnLastFiledon(detailLocator.locator("div[id*=\"LatestAnnualFiling_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());

                        }
                        if (detailLocator.locator("div[id*=\"TotalEmployeesMale_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setMale(detailLocator.locator("div[id*=\"TotalEmployeesMale_labelBox\"]").locator("+ div").innerHTML());
                        }

                        if (detailLocator.locator("div[id*=\"TotalCambodianEmployees_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setNumberOfCambodianEmployees(detailLocator.locator("div[id*=\"TotalCambodianEmployees_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"TotalForeignEmployees_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setNumberOfForeignEmployees(detailLocator.locator("div[id*=\"TotalForeignEmployees_labelBox\"]").locator("+ div").innerHTML());
                        }
                        System.out.println("点击address按钮");
                        if (page.locator("a[id*=\"_parentCompanyTab\"]").isVisible()) {

                            //00000070
                            System.out.println("Parent Company Physical Registered Office Address");

                            page.locator("a[id*=\"_parentCompanyTab\"]").click();
                            ////div[@class="appDialogRepeaterRowContent appRowOdd appRowFirst appRowLast"]/div[1]/div[1]/div[1]/div[2]
                            page.waitForTimeout(1000);
                            page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                            if (detailLocator.locator("div[id*=\"-ParentCompanyName_labelBox\"]").locator("+ div").isVisible()) {
                                companyEntity.setFullNameParentCompany(detailLocator.locator("div[id*=\"ParentCompanyName_labelBox\"]").locator("+ div").innerHTML());
                            }

                            if (detailLocator.locator("div[id*=\"-ParentRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                                companyEntity.setDateRegistrationParentCompany(detailLocator.locator("div[id*=\"-ParentRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                            }
                            if (detailLocator.locator("div[id*=\"-ParentRegistrationCountryCode_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                                companyEntity.setCountryRegistrationParentCompany(detailLocator.locator("div[id*=\"-ParentRegistrationCountryCode_labelBox\"]").locator("+ div").innerHTML());
                            }
                            if (detailLocator.locator("div[id*=\"-StartDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                                companyEntity.setStartDateParentCompany(detailLocator.locator("div[id*=\"-StartDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                            }
                            if (detailLocator.locator("div[class*=\"brViewOverseasCompany-tabsBox-parentCompanyTab-parentCompanyAddressBox-editAddress-categorizerBox-postalAddresses-postalAddress-postal\"]").locator("div[class=\"appAttrValue\"]").isVisible()) {
                                companyEntity.setAddressParentCompany(detailLocator.locator("div[class*=\"brViewOverseasCompany-tabsBox-parentCompanyTab-parentCompanyAddressBox-editAddress-categorizerBox-postalAddresses-postalAddress-postal\"]").locator("div[class=\"appAttrValue\"]").innerHTML());
                            }


                            page.locator("a[id*=\"_addressesTab\"]").click();
                            page.waitForTimeout(1000);
                            page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));

                            //_labelBox
                            //<span class="appLabelText">Physical Registered Office Address</span>
                            System.out.println("Physical Registered Office Address");
                            page.locator("div[aria-labelledby*=\"_addressesTab\"]");
                            companyEntity.setPhysicalRegisteredOfficeAddress(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setAddressStartDate(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/span[1]").innerHTML());

                            companyEntity.setPostalRegisteredOfficeAddress(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setPostalStartDate(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/span[1]").innerHTML());
                            companyEntity.setContactEmail(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setContactTelephoneNumber(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());

                        } else {

                            page.locator("a[id*=\"_addressesTab\"]").click();
                            page.waitForTimeout(1000);
                            page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                            //_labelBox
                            //<span class="appLabelText">Physical Registered Office Address</span>

                            page.locator("div[aria-labelledby*=\"_addressesTab\"]");
                            companyEntity.setPhysicalRegisteredOfficeAddress(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setAddressStartDate(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/span[1]").innerHTML());
                            companyEntity.setPostalRegisteredOfficeAddress(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setPostalStartDate(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/span[1]").innerHTML());
                            companyEntity.setContactEmail(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setContactTelephoneNumber(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());

                        }
                        System.out.println("Director ");
                        page.locator("a[id*=\"_directorsTab\"]").click();
                        page.waitForTimeout(1000);
                        page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                        List<Locator> locators = page.locator("div[aria-labelledby*=\"_directorsTab\"]").locator("div[class=\"appCategory Current\"]").locator("div[class=\"appDialogRepeaterContent\"]").locator("div[class*=\"appDialogRepeaterRowContent\"]").all();

                        System.out.println("locators size:" + locators.size());
                        companyEntity.setCreateTime(LocalDateTime.now());
                        companyEntity.setBusinessId(queryString);
                        this.entityService.save(companyEntity);
                        ArrayList<Director> targetDirectors = new ArrayList<>();
                        if (ObjectUtil.isNotEmpty(locators)) {
                            ArrayList<Director> directors = new ArrayList<>();
                            for (Locator locator : locators) {
                                Director director = new Director();
                                if (locator.innerHTML().length() > 10) {
                                    if (locator.locator("//div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").isVisible()) {
                                        director.setNameKhmer(locator.locator("//div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                                    }
                                    if (locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/DIV[2]").isVisible()) {
                                        director.setNameEnglish(locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/DIV[2]").innerHTML());
                                    }
                                    if (locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[2]").isVisible()) {
                                        director.setPostalRegisteredOfficeAddress(locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[1]/DIV[2]").innerHTML());
                                    }
                                    if (locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[3]/DIV[1]/DIV[1]/DIV[2]").isVisible()) {
                                        director.setTelephone(locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[3]/DIV[1]/DIV[1]/DIV[2]").innerHTML());
                                    }
                                    if (locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[4]/DIV[2]").isVisible()) {
                                        director.setChairmanOfTheBoardOfDirectors(locator.locator("//DIV[2]/DIV[1]/DIV[1]/DIV[1]/DIV[4]/DIV[2]").innerHTML());
                                    }
                                    director.setCreateTime(LocalDateTime.now());
                                    director.setEntityId(companyEntity.getId());
                                    directors.add(director);
                                }
                            }

                            for (Director director : directors) {
                                if (!Objects.equals(director.getChairmanOfTheBoardOfDirectors(), "No")) {
                                    targetDirectors.add(director);
                                }
                            }
                            for (Director director : directors) {
                                if (Objects.equals(director.getChairmanOfTheBoardOfDirectors(), "No")) {
                                    targetDirectors.add(director);
                                }
                            }
                        }
                        companyEntity.setDirectors(targetDirectors);
                        System.out.println(companyEntity.toString());
                        this.directorService.saveBatch(companyEntity.getDirectors());
                        page.goBack();
                        System.out.println("数据获取完毕");
                    }

                    System.out.println("开始重置");
                    page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                    page.click("text=Reset Search");

                } catch (Exception e) {
                    System.err.println("出现异常，异常数字为:" + queryString + "持续进行。");
                    e.printStackTrace();
                    page.goBack();
                    page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                    page.click("text=Reset Search");
                }
            }

            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }
        logger.info("执行完毕，" + start + ":" + end);
        logger.info("执行完毕，" + start + ":" + end);
        logger.info("执行完毕，" + start + ":" + end);
    }

    @Async("taskExecutor")
    public void startTaskByList(List<CompanyEntity> companyEntities, String name) {
        logger.info("Creating " + name + ",start:" + companyEntities.size());

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false).setSlowMo(250).setTimeout(40000));
            Page page = browser.newPage();
            page.navigate("https://www.businessregistration.moc.gov.kh/");
            page.click("a[class=\"menu-toggle injected\"]");
            page.click("text=Search Entity");
            for (CompanyEntity companyEntity : companyEntities) {
                System.out.println(companyEntity.getBusinessId() + "|" + "执行搜索字符串填入");
                String queryString = companyEntity.getBusinessId();
                System.out.println("按钮点击" + "|" + queryString);
                while (true) {
                    page.waitForTimeout(1000);
                    if (page.locator("input[name=\"QueryString\"]").isVisible()) {
                        page.fill("input[name=\"QueryString\"]", queryString);
                        break;
                    }
                }
//                page.fill("input[name=\"QueryString\"]", "00000178");
                try {

//                page.click("text=Search");
                    System.out.println("按钮执行完毕");

                    page.waitForResponse("**/cambodia-master/viewInstance/update.html*", () -> {
                        page.locator("//div[@class=\"appTabSelected\"]").locator("span:text-is(\"Search\")").click();
                    });
                    page.waitForTimeout(2000);
                    page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));

                    String first = "//body/div[1]/div[1]/div[5]/div[1]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[4]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/a[1]/span[2]";
                    Locator firstLocator = page.locator(first);

                    if (firstLocator.isVisible()) {
                        System.out.println("数据获取开始");
                        firstLocator.click();
                        page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                        Thread.sleep(1000);
//                    hashMap.put()
                        // //li[@class="appTabPostSelected"]/a[1]/span[1]
//                    map.put("CompanyNameInKhmer",page.locator("//div[@class=\"appRepeaterRo
//                    wContent appRowOdd appRowFirst appRowLast\"]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                        // 获取紧邻的下一个同级div
                        //page.evaluate("div[css*=\"brViewOverseasCompany-tabsBox-detailsTab-details-historicalInformationBox\"]");
                        ElementHandle element = page.querySelector(".brViewOverseasCompany-tabsBox-detailsTab-details-historicalInformationBox");
                        if (element != null) {
                            element.evaluate("node => node.remove()");
                            element.dispose(); // 释放资源
                            System.out.println("删除历史记录");
                        }
                        element = page.querySelector(".brViewLocalCompany-tabsBox-detailsTabChangedPOC-details-historicalInformationBox");
                        if (element != null) {
                            element.evaluate("node => node.remove()");
                            element.dispose(); // 释放资源
                            System.out.println("删除历史记录");
                        }
                        Locator detailLocator;
                        if (page.locator("text=\"Show company name history\"").isVisible()) {
                            System.out.println("Show company name history");
                            detailLocator = page.locator("div[css*=\"brViewLocalCompany-tabsBox-detailsTabChangedPOC-details-localDetailsBox\"]");
                        } else {
                            detailLocator = page.locator("body");
                        }

//                        Locator detailLocator = page.locator("div[css*=\"brViewLocalCompany-tabsBox-detailsTabChangedPOC-details\"]");
                        if (detailLocator.locator("div[id*=\"Name_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setCompanyNameInEnglish(detailLocator.locator("div[id*=\"Name_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"NameInKhmer_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setProposedNameInKhmer(detailLocator.locator("div[id*=\"NameInKhmer_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"OriginalVersionIdentifier_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setOriginalEntityIdentifier(detailLocator.locator("div[id*=\"OriginalVersionIdentifier_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"Status_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setCompanyStatus(detailLocator.locator("div[id*=\"Status_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"-RegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                            companyEntity.setIncorporationDate(detailLocator.locator("div[id*=\"-RegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"TIN_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setTaxIdentificationNumber(detailLocator.locator("div[id*=\"TIN_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"TINRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                            companyEntity.setTaxRegistrationDate(detailLocator.locator("div[id*=\"TINRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"LatestAnnualFiling_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                            companyEntity.setAnnualReturnLastFiledon(detailLocator.locator("div[id*=\"LatestAnnualFiling_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());

                        }
                        if (detailLocator.locator("div[id*=\"TotalEmployeesMale_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setMale(detailLocator.locator("div[id*=\"TotalEmployeesMale_labelBox\"]").locator("+ div").innerHTML());
                        }

                        if (detailLocator.locator("div[id*=\"TotalCambodianEmployees_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setNumberOfCambodianEmployees(detailLocator.locator("div[id*=\"TotalCambodianEmployees_labelBox\"]").locator("+ div").innerHTML());
                        }
                        if (detailLocator.locator("div[id*=\"TotalForeignEmployees_labelBox\"]").locator("+ div").isVisible()) {
                            companyEntity.setNumberOfForeignEmployees(detailLocator.locator("div[id*=\"TotalForeignEmployees_labelBox\"]").locator("+ div").innerHTML());
                        }
                        System.out.println("点击address按钮");
                        if (page.locator("a[id*=\"_parentCompanyTab\"]").isVisible()) {

                            //00000070
                            System.out.println("Parent Company Physical Registered Office Address");

                            page.locator("a[id*=\"_parentCompanyTab\"]").click();
                            ////div[@class="appDialogRepeaterRowContent appRowOdd appRowFirst appRowLast"]/div[1]/div[1]/div[1]/div[2]
                            page.waitForTimeout(1000);
                            page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                            if (detailLocator.locator("div[id*=\"-ParentCompanyName_labelBox\"]").locator("+ div").isVisible()) {
                                companyEntity.setFullNameParentCompany(detailLocator.locator("div[id*=\"ParentCompanyName_labelBox\"]").locator("+ div").innerHTML());
                            }

                            if (detailLocator.locator("div[id*=\"-ParentRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                                companyEntity.setDateRegistrationParentCompany(detailLocator.locator("div[id*=\"-ParentRegistrationDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                            }
                            if (detailLocator.locator("div[id*=\"-ParentRegistrationCountryCode_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                                companyEntity.setCountryRegistrationParentCompany(detailLocator.locator("div[id*=\"-ParentRegistrationCountryCode_labelBox\"]").locator("+ div").innerHTML());
                            }
                            if (detailLocator.locator("div[id*=\"-StartDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").isVisible()) {
                                companyEntity.setStartDateParentCompany(detailLocator.locator("div[id*=\"-StartDate_labelBox\"]").locator("+ div").locator("span[class=\"appOffScreenText\"]").innerHTML());
                            }
                            if (detailLocator.locator("div[class*=\"brViewOverseasCompany-tabsBox-parentCompanyTab-parentCompanyAddressBox-editAddress-categorizerBox-postalAddresses-postalAddress-postal\"]").locator("div[class=\"appAttrValue\"]").isVisible()) {
                                companyEntity.setAddressParentCompany(detailLocator.locator("div[class*=\"brViewOverseasCompany-tabsBox-parentCompanyTab-parentCompanyAddressBox-editAddress-categorizerBox-postalAddresses-postalAddress-postal\"]").locator("div[class=\"appAttrValue\"]").innerHTML());
                            }


                            page.locator("a[id*=\"_addressesTab\"]").click();
                            page.waitForTimeout(1000);
                            page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));

                            //_labelBox
                            //<span class="appLabelText">Physical Registered Office Address</span>
                            System.out.println("Physical Registered Office Address");
                            page.locator("div[aria-labelledby*=\"_addressesTab\"]");
                            companyEntity.setPhysicalRegisteredOfficeAddress(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setAddressStartDate(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/span[1]").innerHTML());

                            companyEntity.setPostalRegisteredOfficeAddress(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setPostalStartDate(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[2]/span[1]").innerHTML());
                            companyEntity.setContactEmail(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());
                            companyEntity.setContactTelephoneNumber(page.locator("//div[@class=\"appTabSelected\"]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]").innerHTML());

                        }
                        System.out.println("Director ");
                        page.locator("a[id*=\"_directorsTab\"]").click();
                        page.waitForTimeout(1000);
                        page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                        List<Locator> locators = page.locator("div[aria-labelledby*=\"_directorsTab\"]").locator("div[class=\"appCategory Current\"]").locator("div[class=\"appDialogRepeaterContent\"]").locator("div[class*=\"appDialogRepeaterRowContent\"]").all();

                        System.out.println("locators size:" + locators.size());
                        companyEntity.setCreateTime(LocalDateTime.now());
                        companyEntity.setBusinessId(queryString);
                        this.entityService.updateById(companyEntity);
                        page.goBack();
                        System.out.println("数据获取完毕");
                    }

                    System.out.println("开始重置");
                    page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                    page.click("text=Reset Search");

                } catch (Exception e) {
                    System.err.println("出现异常，异常数字为:" + queryString + "持续进行。");
                    e.printStackTrace();
                    page.goBack();
                    page.waitForLoadState(LoadState.NETWORKIDLE, new Page.WaitForLoadStateOptions().setTimeout(5000));
                    page.click("text=Reset Search");
                }
            }
            Thread.sleep(5000);
        } catch (InterruptedException e) {
        }

    }

    @Async("taskExecutor")
    public void saveToExcel(ArrayList<CompanyEntity> entities, String name) {
//         Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(null, "简单导出测试表"), Entity.class, entities);

        try {
            ExportParams exportParams = new ExportParams();
            exportParams.setType(ExcelType.XSSF);
            exportParams.setTitle("合同信息");
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CompanyEntity.class, entities);

            //先创建父文件夹
            FileUtil.mkParentDirs(name);
            File file = FileUtil.file(name);
            FileOutputStream fos = new FileOutputStream(file);
            workbook.write(fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
